package com.vkdasari.youtube.upload;

import java.awt.GridLayout;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.util.AuthenticationException;
import com.vkdasari.youtube.util.ZebraConstants;

public class YouTubeSessionHandler {
	
	private static YouTubeSessionHandler instance;
	private String username;
	private String password;
	private YouTubeService service;

	private static final Logger log = Logger.getLogger(YouTubeSessionHandler.class);
	
	public static YouTubeSessionHandler getInstance(){
		if(instance == null){
			instance = new YouTubeSessionHandler();
		}
		
		return instance;
	}

	private YouTubeSessionHandler(){
		
	}
	
	public void login(){
		
	}
	
	public void logout(){
		
	}
	
	public boolean isLoggedIn(){
		return false;
	}
	
	
	/**
	 * @return the service
	 */
	public YouTubeService getService() {
		if(service == null || username == null || username.isEmpty() || password == null || password.isEmpty()){
			service = new YouTubeService(
					"VJ-YouTube-Client", ZebraConstants.DEVELOPER_KEY);
			
			String[] credits = getIDandPassword();

			username = credits[0];
			password = credits[1];

			try {
				service.setUserCredentials(username, password);
			} catch (AuthenticationException e) {
				log.info("Invalid login credentials.");
			}
		}
		return service;
	}
	
	/**
	 * Prompts for both User Name and Password
	 * 
	 * @return
	 */
	private String[] getIDandPassword() {
		JPanel connectionPanel;

		// Create the labels and text fields.
		JLabel userNameLabel = new JLabel("User ID:   ", JLabel.RIGHT);
		JTextField userNameField = new JTextField("", 30);

		JLabel passwordLabel = new JLabel("Password:   ", JLabel.RIGHT);
		JTextField passwordField = new JPasswordField("", 30);

		String[] ConnectOptionNames = { "Login", "Cancel" };

		connectionPanel = new JPanel(false);
		connectionPanel.setLayout(new BoxLayout(connectionPanel,
				BoxLayout.X_AXIS));
		
		JPanel namePanel = new JPanel(false);
		namePanel.setLayout(new GridLayout(0, 1));
		namePanel.add(userNameLabel);
		namePanel.add(passwordLabel);
		
		JPanel fieldPanel = new JPanel(false);
		fieldPanel.setLayout(new GridLayout(0, 1));
		fieldPanel.add(userNameField);
		fieldPanel.add(passwordField);
		
		connectionPanel.add(namePanel);
		connectionPanel.add(fieldPanel);
		
		// Connect or quit
		if (JOptionPane.showOptionDialog(null, connectionPanel,
				"YouTube Credentials", JOptionPane.OK_CANCEL_OPTION,
				JOptionPane.INFORMATION_MESSAGE, null, ConnectOptionNames,
				ConnectOptionNames[0]) != 0) {
			System.exit(0);
		}

		return new String[] { userNameField.getText(), passwordField.getText() };
	}
	
}
